/**
 * time: 2025-09-12
 * author: XJ
 * description: 申请实验左侧舱段——载荷——事件树
 */
import React, { useEffect, useMemo, useState } from 'react';
import { Tree } from 'antd';
import type { GetProps, TreeDataNode } from 'antd';
import Search from 'antd/es/input/Search';
import { getParamByActionId, getXmlTree } from '@/services/apis/dataManager';
import { useModel } from '@umijs/max';
import { initLoadTree } from '@/services/apis/experiment';

type DirectoryTreeProps = GetProps<typeof Tree.DirectoryTree>;

const { DirectoryTree } = Tree;
function HighlightText({ text, keyword }: any) {
  if (!keyword) return <>{text}</>;
  const parts = text.split(new RegExp(`(${keyword})`, 'gi'));
  return (
    <>
      {parts.map((part: any, i: any) =>
        part.toLowerCase() === keyword.toLowerCase() ? (
          <span key={i} style={{ color: 'red', fontWeight: 'bold' }}>
            {part}
          </span>
        ) : (
          <span key={i}>{part}</span>
        ),
      )}
    </>
  );
}

const LeftActionTree: React.FC = () => {
  const { leftTreeModel, setLeftTreeModel } = useModel('ExperimentApplication.leftTree');

  const onSelect: DirectoryTreeProps['onSelect'] = (keys, info) => {
    const { node } = info;
    if (!node.isLeaf) return;
  };

  const onExpand: DirectoryTreeProps['onExpand'] = (keys, info) => {
    setLeftTreeModel({ ...leftTreeModel, expanedKeys: keys });
  };

  useEffect(() => {
    initLoadTree({}).then((res: any) => {
      const { success, msg, data } = res;
      if (success) {
        setLeftTreeModel((prev) => ({ ...prev, treeData: transformTree(data) }));
      }
    });
  }, []);

  const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { value } = e.target;
    setLeftTreeModel({ ...leftTreeModel, searchValue: value });
  };

  const filterTree = (tree: any, searchValue: String, expandedKeys = new Set(), parentKey = null) =>  {
    return tree
      .map((node: any) => {
        const filteredChildren = node.children
          ? filterTree(node.children, searchValue, expandedKeys, node.id)
          : undefined;

        const isMatch = node.name.includes(searchValue);

        if (
          isMatch ||
          (filteredChildren && filteredChildren.length > 0) ||
          node.name === '光学舱'
        ) {
          if (parentKey) {
            expandedKeys.add(parentKey);
          }

          return {
            ...node,
            title: <HighlightText text={node.name} keyword={searchValue} />,
            ...(filteredChildren && filteredChildren.length > 0
              ? { children: filteredChildren }
              : {}),
          };
        }

        return null;
      })
      .filter(Boolean);
  }

  const transformTree = (tree:any, keyword = '') => {
    return tree.map((node:any) => {
    const transformed = {
      ...node,
      title: <HighlightText text={node.name} keyword={keyword} />,
      isLeaf: !node.children
    };

    // 只有真的有子节点时才挂 children
    if (node.children && node.children.length > 0) {
      transformed.children = transformTree(node.children, keyword);
    }

    return transformed;
  });
  }

  const treeDataProxy = useMemo(() => {
    if (!leftTreeModel.searchValue) {
      setLeftTreeModel({ ...leftTreeModel, autoExpandedKeys: [] }); // 搜索为空时收起
      return leftTreeModel.treeData.map((node) => ({
        ...node,
        name: <HighlightText text={node.name} keyword={''} />,
      }));
    } else {
      const expandedKeys = new Set();
      const filtered = filterTree(leftTreeModel.treeData, leftTreeModel.searchValue, expandedKeys);
      setLeftTreeModel({ ...leftTreeModel, autoExpandedKeys: [...expandedKeys] }); // 更新展开的节点
      return filtered;
    }
  }, [leftTreeModel.searchValue, leftTreeModel.treeData]);

  return (
    <div
      style={{
        height: 'calc(100% - 64px)',
        overflowY: 'hidden',
        backgroundColor:"#141414"
      }}
    >
      <Search style={{ marginBottom: 8 }} placeholder="请输入关键字" onChange={onChange} />
      <DirectoryTree
        rootStyle={{
          height: 'calc(100% - 40px)',
          overflowY: 'auto',
          maxHeight: 'calc(100% - 40px)',
        }}
        showLine
        multiple
        expandedKeys={[
          ...new Set([...leftTreeModel.expanedKeys, ...leftTreeModel.autoExpandedKeys]),
        ]}
        fieldNames={{ title: 'title', key: 'id' }}
        onSelect={onSelect}
        onExpand={onExpand}
        treeData={treeDataProxy}
      />
    </div>
  );
};

export default LeftActionTree;
